package com.snail.billing.wxapi;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;

import com.snail.billing.DataCache;
import com.tencent.mm.sdk.constants.ConstantsAPI;
import com.tencent.mm.sdk.modelbase.BaseReq;
import com.tencent.mm.sdk.modelbase.BaseResp;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.sdk.openapi.WXAPIFactory;

public class WXPayEntryActivity extends Activity implements IWXAPIEventHandler {

	private static final String TAG = WXPayEntryActivity.class.getName();
	public static final String WXPAY_RESULT_RECEIVER = "com.snail.billing.wxpay_result_receiver";

	private IWXAPI api;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		String orderResponse = DataCache.getInstance().paymentParams.orderResponse;
		try {
			JSONObject paymentParams = new JSONObject(orderResponse).getJSONObject("paymentParams");
			api = WXAPIFactory.createWXAPI(this, paymentParams.getString("appid"));
			api.handleIntent(getIntent(), this);
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}

	@Override
	protected void onNewIntent(Intent intent) {
		super.onNewIntent(intent);
		setIntent(intent);
		if (api != null) {
			api.handleIntent(intent, this);
		}
	}

	@Override
	public void onReq(BaseReq req) {
	}

	@Override
	public void onResp(BaseResp resp) {
		Log.i(TAG, "onPayFinish, errCode=" + resp.errCode);
		if (resp.getType() == ConstantsAPI.COMMAND_PAY_BY_WX) {
			Intent intent = new Intent(WXPAY_RESULT_RECEIVER);
			intent.putExtra("wxcode", resp.errCode);
			sendBroadcast(intent);
			finish();
		}
	}
}